﻿/************************************************
*
* Copyright(c) ZeeGuo.com
*
* CLR : 4.0.30319.296
*
* FileName : DownLoader.cs
*
* Author : Kurodo
*
* CreatTime : 2013/7/5 17:09:43
*           
*************************************************/

using System;
using System.IO;
using System.Net;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using ComicSpider.Model;

namespace ComicSpider
{
    public class DownLoader
    {
        public event AsyncCompletedEventHandler DownloadFilesCompleted;

        private int totalCount = 0;
        private int count = 0;

        public IComicStorage Storage
        {
            get;
            set;
        }

        public string Folder
        {
            get
            {
                if (this.Folder == string.Empty)
                    return "D:";
                else
                    return this.Folder;
            }
            set
            {
                this.Folder = value;
            }
        }

        public void DownLoad(List<string> uriList)
        {
            totalCount = uriList.Count;

            foreach (var uri in uriList)
            {
                string file = Storage.StorageComic(uri, this.Folder);

                Download(uri, file);
            }
        }

        public void DownloadSingle(List<string> uriList,string file)
        {
            foreach (string uri in uriList)
            {
                WebClient client = new WebClient();
                client.DownloadFile(uri, file);
            }
        }

        public void Download(string uri,string file)
        {
            WebClient client = new WebClient();
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(onCompleted);
            client.DownloadFileAsync(new Uri(uri), file);
        }

        public void onCompleted(object sender, AsyncCompletedEventArgs e)
        {
            count++;
            if (count == totalCount)
            {
                AsyncCompletedEventArgs args = new AsyncCompletedEventArgs(null, false, null);
                DownloadFilesCompleted.Invoke(this, args);
            }
        }
    }
}
